# -*- coding: utf-8 -*-

# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html

import math
import re
import time

import pymongo

from duanwenxue.items import Posts

class MongoPipeline(object):
    
    def __init__(self, mongo_uri, mongo_db):
        """
        good
            :param self: self
            :param mongo_uri: mongo_uri
            :param mongo_db: mongo_db
        """
        self.mongo_uri = mongo_uri
        self.mongo_db = mongo_db

    @classmethod
    def from_crawler(cls, crawler):
        """
        docstring here
            :param cls: cls
            :param crawler: crawler
        """
        return cls(
            mongo_uri=crawler.settings.get('MONGO_URI'),
            mongo_db=crawler.settings.get('MONGO_DB')
        )

    def open_spider(self, spider):
        """
        docstring here
            :param self: self
            :param spider: spider
        """
        self.client = pymongo.MongoClient(self.mongo_uri)
        self.db = self.client[self.mongo_db]

    def process_item(self, item, spider):
        """
        docstring here
            :param self: self
            :param item: item
            :param spider: spider
        """
        name = item.__class__.__name__
        self.db[name].insert(dict(item))
        return item

    def close_spider(self, spider):
        """
        docstring here
            :param self: self
            :param spider: spider
        """
        self.client.close()
